<template>
  <div class="hawkContent">
    <hawk-breadcrumb></hawk-breadcrumb>
    <el-row :gutter="20" style="padding-left: 20px">
      <el-col :span="5" style="display: flex; align-items: center">
        <span style="width: 90px; color: #666666; font-size: 13px">所属地区：</span>
        <el-select clearable v-model="queryForm.query.areaId" filterable
                   placeholder="请选择地区">
          <el-option v-for="(item, index) in areaList" :key="index"
                     :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-col>
      <el-col :span="5" style="display: flex; align-items: center">
        <span style="width: 90px; color: #666666; font-size: 13px">公司名称：</span>
        <el-input placeholder="请输入公司名称搜索" v-model="queryForm.query.company">
        </el-input>
      </el-col>

      <el-col :span="4">
        <el-button type="hawkSearch" @click="init(true)">搜索</el-button>
        <el-button plain @click="reSet">重置</el-button>
      </el-col>
      <el-col :span="4"
              style="float: right; text-align: right; padding-right: 30px">
        <el-button type="hawkCreate" @click="edit">创建公司</el-button>
      </el-col>
    </el-row>
    <!-- { key: 'createTime', label: '创建时间' }, -->
    <hawk-table v-model="multipleSelection" :table-data="tableData"
                :page="queryForm.page" :number="true"
                @selectionChange="handleSelectionChange" :options="[
        { key: 'areaName', label: '地区名称' },
        { key: 'company', label: '公司名称' },
        { key: 'handle', label: '操作' },
      ]">
      <template #areaName="{ row }">
        <span>{{ currAreaName(row.areaId)  }}</span>
        <!-- <span>{{ row.areaId }}</span> -->
      </template>

      <template #company="{ row }">
        <span>{{ row.name }}</span>
      </template>

      <template #createTime="{ row }">
        <span>{{ dataFormat(row.createTime, 'yyyy-MM-dd hh:mm:ss')}}</span>
      </template>

      <template #handle="{ row }">
        <span class="hawk-text-btn" @click="edit(row)">编辑</span>
        <span class="hawk-text-divider">|</span>
        <span class="hawk-text-btn" @click="del(row)">删除</span>
      </template>

    </hawk-table>

    <div class="bottom-btns">
      <div class="bottom-btns-left">
        <div class="bottom-btns-left-num">
          {{ multipleSelection.length }} 选择
        </div>
        <el-button type="hawkDelete" @click="catchDel">批量删除</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page.sync="queryForm.page.current"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="queryForm.page.size"
                     layout=" prev, pager, next,sizes" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="formTitle" :visible.sync="addDialogVisible" width="20%"
               :close-on-click-modal="false" @close="addDialogClosed">
      <!-- 内容主题区 -->
      <el-form :model="addForm" label-position="right" :rules="addFormRules"
               ref="addFormRef" label-width="90px">
        <el-form-item label="所属地区" prop="areaId">
          <el-select clearable v-model="addForm.areaId" placeholder="请选择地区"
                     @change="onAreaChange">
            <el-option v-for="(item, index) in areaList" :key="index"
                       :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author 韩梦远
 * @description 公司字典
 * @api 后台接口地址
 * @since 2021-10-08
 * @update 代码更新时间
 * @modifier 修改人
 * @bug 无
 * @version v1.0.0
 */
import {
  getAllCompany, // 获得所有公司，没用到
  getList, // 根据名称分页查询
  doDelete,
  isNameHave,
  doAddCompany,
  doEdit,
} from '@/api/assets/dictionaries/company'

import { getAll as getArea } from '@/api/assets/dictionaries/area'


export default {
  data () {

    let nameValide = async (rule, value, callback) => {

      if (!value) {
        return
      }

      console.log(value);

      // 如果是 编辑，且与之前同名，不做校验
      if (this.addForm.id) {
        if (this.addForm.areaId == this.cacheAreaComName.areaId
          && this.addForm.name == this.cacheAreaComName.name
        ) {
          callback()
          return
        }
      }


      let areaId = this.addForm.areaId
      let ret = await isNameHave(value, areaId)

      console.log(ret);

      if (ret.code == 20000 && ret.data) {
        callback(new Error('公司已经存在'))
        return
      }

      callback()


    }

    return {

      cacheAreaComName: {
        name: '',
        areaId: ''
      },

      multipleSelection: [],
      addDialogVisible: false,
      total: 0,
      formTitle: '',
      queryForm: {
        query: {
          company: '',
          areaId: '',
        },
        page: {
          current: 1,
          size: 10,
        },
      },
      tableData: [],
      addForm: {
        name: '', // 公司名称
        areaId: '',
      },
      addFormRules: {

        name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '公司名称的长度在3-20个字符之间',
            trigger: 'blur',
          },
          { validator: nameValide, trigger: 'blur' }
        ],
        areaId: [
          { required: true, message: '请选择所属地区', trigger: 'change' },
        ],
      },
      areaList: [],
    }
  },
  computed: {

  },
  methods: {

    onAreaChange () {
      this.$refs.addFormRef.validateField('name');
    },
    dataFormat (date, format) {
      return this.transformDateFormat(date, format)
    },
    currAreaName (rowId) {
      if (this.areaList.length == 0) return ""
      let tt = this.areaList.find(item => { return item.id == rowId })
      if (tt) {
        return tt.name
      } else {
        return ''
      }

    },

    async getAreaList () {
      const res = await getArea()
      console.log(JSON.stringify(res));
      this.areaList = res.data
      // let obj = {
      //   name: '请选择地区',
      //   id: 0,
      // }
      // this.areaList.unshift(obj)
    },
    reSet () {
      this.queryForm = this.$options.data().queryForm
      this.init()
    },
    async init (type) {
      console.log("-----111------------");
      if (type) this.queryForm.page.current = 1
      const { data } = await getList(this.queryForm)
      console.log(JSON.stringify(data));
      this.tableData = data.records
      this.total = data.total
      this.multipleSelection = []
    },
    handleSizeChange (val) {
      this.queryForm.page.size = val
      this.init()
    },
    handleCurrentChange (val) {
      this.queryForm.page.current = val
      this.init()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    catchDel () {
      let list = []
      this.multipleSelection.forEach((item) => {
        list.push(item.id)
      })
      // console.log(list);
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {
          let ret = await doDelete(list)

          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.multipleSelection.length == this.tableData.length) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }






        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    edit (row) {
      if (!row.id) {
        this.formTitle = '创建公司'
      } else {
        this.formTitle = '修改公司'

        this.addForm = Object.assign({}, row)

        // 编辑时，缓存信息
        this.cacheAreaComName = {
          name: this.addForm.name,
          areaId: this.addForm.areaId
        }

      }
      this.addDialogVisible = true
    },
    addDialogClosed () {
      this.addForm = this.$options.data().addForm
      this.$refs.addFormRef.resetFields()

      this.addDialogVisible = false
      this.init()
    },
    save () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        // 编辑公司
        if (this.addForm.id) {

          let { message } = await doEdit(this.addForm)
          this.$msg.success(message)
          this.multipleSelection = []

        } else {
          // 新建 
          let { message } = await doAddCompany({
            areaId: this.addForm.areaId,
            name: this.addForm.name
          })

          console.log(message);

          this.multipleSelection = []
          this.$msg.success(message)
        }
        this.addDialogClosed()
      })
    },
    del (row) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(async () => {

          console.log([row.id]);
          let ret = await doDelete([row.id])
          console.log(ret);
          if (ret.code == 20000) {

            let type = ''
            if (ret.data) {
              ret.message = '删除成功'
              type = 'success'
            } else {
              type = 'error'
            }
            this.$message({
              type: type,
              message: ret.message,
            })

            // console.log(this.multipleSelection.length);
            if (this.tableData.length == 1) {
              this.queryForm.page.current = this.queryForm.page.current - 1
              if (this.queryForm.page.current < 1) {
                this.queryForm.page.current = 1
              }
            }

            this.multipleSelection = []
            this.init()


          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  created () {
    this.getAreaList()
    this.init()
  },
}
</script>
<style lang="scss" scoped></style>
